package com.googlecode.agscrum.model.service;

import java.util.List;

import com.googlecode.agscrum.model.entity.User;
import com.googlecode.agscrum.model.exceptions.GScrumDomainException;
import com.googlecode.agscrum.model.exceptions.GScrumDomainException.TypeMessage;
import com.googlecode.agscrum.model.util.Criteria;
import com.googlecode.agscrum.model.util.Restrictions;

public class UserServiceImpl extends ServiceImpl<User, Long> implements
		UserService {

	@Override
	public User readByLogin(String login) throws GScrumDomainException {
		Criteria criteria = Criteria
				.getInstance("User.findByLogin", User.class).addAnd(
						Restrictions.eq("u.login", login));
		List<User> users = readByCriteria(criteria);
		if (users != null && users.size() == 1) {
			return users.get(0);
		} else {
			throw new GScrumDomainException(messageFactory.createMessage(
					"user.login.not.exist", null, TypeMessage.WARNING));
		}
	}

	@Override
	public User changePassword(User user, String oldPassword,
			String newPassword, String repeatPassword)
			throws GScrumDomainException {
		try {
			user.changePassword(oldPassword, newPassword, repeatPassword);
			user = save(user);
		} catch (IllegalArgumentException e) {
			throw new GScrumDomainException(messageFactory.createMessage(
					"user.changePassword.generic.error", null,
					TypeMessage.ERROR));
		}
		return user;
	}
}
